package com.grablist.feihu.grablist.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;

import com.grablist.feihu.grablist.bean.ResponInfo;
import com.grablist.feihu.grablist.comm.Constants;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;

import com.grablist.feihu.grablist.R;


/**
 * Created by xuweihua on 16/7/31.
 */
public class ShareUtils {
    private final static String QQ_APP_ID = "1106675594";

    public final static String WB_APP_ID = "3566189280";

    public final static String WX_APP_ID = Constants.APP_ID;

    private Activity activity;
    private IWXAPI wxApi;
    private IWeiboShareAPI wbApi;
    private ResponInfo url;


    public ShareUtils(Activity activity, ResponInfo url) {
        this.activity = activity;
        this.url = url;
    }

    public void setWbApi(IWeiboShareAPI wbApi) {
        this.wbApi = wbApi;
    }

    public void setWxApi(IWXAPI wxApi) {
        this.wxApi = wxApi;
    }

    public void pyqShare() {
        if (!IsInstallUtils.isWXAppInstalledAndSupported(activity, wxApi)) {
            ToastUtils.shortToast("未安装微信");
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url.getSpec();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = url.getTitle();
        msg.description = url.getDetail();
        Bitmap bitmap = null;
        if (StringUtils.isEmpty(url.getImg())) {
            bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.icon_share);
            msg.setThumbImage(bitmap);
        } else {
            try {
                bitmap = BitmapFactory.decodeStream(new URL(url.getImg()).openStream());
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 120, 150, true);
                msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
            } catch (Exception e) {

            }
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = System.currentTimeMillis() + "";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        wxApi.sendReq(req);
        if (bitmap != null) {
            bitmap.recycle();
        }


    }


    public void wxShare() {
        if (!IsInstallUtils.isWXAppInstalledAndSupported(activity, wxApi)) {
            ToastUtils.shortToast("未安装微信");
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url.getSpec();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = url.getTitle();
        msg.description = url.getDetail();
        Bitmap bitmap = null;
        if (StringUtils.isEmpty(url.getImg())) {
            bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.icon_share);
            msg.setThumbImage(bitmap);
        } else {
            try {
                bitmap = BitmapFactory.decodeStream(new URL(url.getImg()).openStream());
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 120, 150, true);
                msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
            } catch (Exception e) {

            }
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = System.currentTimeMillis() + "";
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        wxApi.sendReq(req);
        if (bitmap != null) {
            bitmap.recycle();
        }
    }

    public void dxShare() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setType("text/plain"); //纯文本
        // 图片分享
//        intent.setType("image/png");
        // 添加图片
//        File f = new File("/sdcard/sd.png");
//        Uri u = Uri.fromFile(f);
//        intent.putExtra(Intent.EXTRA_STREAM, u); //添加图片
        intent.putExtra(Intent.EXTRA_SUBJECT, url.getTitle() + url.getDetail());
        intent.putExtra(Intent.EXTRA_TEXT, url);

        activity.startActivity(Intent.createChooser(intent, "分享好友"));
    }

    public void qqShare(IUiListener iUiListener) {
//        if (!IsInstallUtils.isQQClientAvailable(MyApplication.context)) {
//            ToastUtils.shortToast("未安装QQ");
//            return;
//        }
        Tencent mTencent = Tencent.createInstance(QQ_APP_ID, activity);
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, url.getTitle());
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, url.getDetail());
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url.getSpec());
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, activity.getString(R.string.app_name));
//        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,"android.resource://"+activity.getPackageName()+ File.separator + R.mipmap.icon_share);
        mTencent.shareToQQ(activity, params, iUiListener);
    }

    public void qzoneShare(IUiListener iUiListener) {
//        if (!IsInstallUtils.isQQClientAvailable(MyApplication.context)) {
//            ToastUtils.shortToast("未安装QQ");
//            return;
//        }
        Tencent mTencent = Tencent.createInstance(QQ_APP_ID, activity);
        Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, url.getTitle());
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, url.getDetail());
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url.getSpec());
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());
        mTencent.shareToQzone(activity, params, iUiListener);
    }

    public void wbShare() {
//        WebpageObject mediaObject = new WebpageObject();
//        mediaObject.identify = Utility.generateGUID();
//        mediaObject.title = SHARE_TITLE;
//        mediaObject.description = SHARE_DES;
//        Bitmap  bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher);
//        // 设置 Bitmap 类型的图片到视频对象里
//        // 设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//        mediaObject.setThumbImage(bitmap);
//        mediaObject.actionUrl = SHARE_URL;
//        mediaObject.defaultText = SHARE_TITLE;

        TextObject mediaObject = new TextObject();
        mediaObject.title = url.getTitle();
        mediaObject.text = url.getDetail();
        mediaObject.description = url.getDetail();
        mediaObject.actionUrl = url.getSpec();

        WeiboMessage weiboMessage = new WeiboMessage();
        weiboMessage.mediaObject = mediaObject;
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;
        wbApi.sendRequest(activity, request);
    }

//    private String getRealFilePath(final Uri uri ) {
//        if ( null == uri ) return null;
//        final String scheme = uri.getScheme();
//        String data = null;
//        if ( scheme == null )
//            data = uri.getPath();
//        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
//            data = uri.getPath();
//        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
//            Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
//            if ( null != cursor ) {
//                if ( cursor.moveToFirst() ) {
//                    int index = cursor.getColumnIndex( ImageColumns.DATA );
//                    if ( index > -1 ) {
//                        data = cursor.getString( index );
//                    }
//                }
//                cursor.close();
//            }
//        }
//        return data;
//    }

    /**
     * 把网络资源图片转化成bitmap
     *
     * @param url 网络资源图片
     * @return Bitmap
     */
    public static Bitmap GetLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    /**
     * 发送文件
     *
     * @param context
     * @param file
     */
    public static void sendFileByOtherApp(Context context, File file) {
//        File file = new File(path);
        if (file.exists()) {
            String type = getMimeType(file.getPath());
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            shareIntent.setType(getMimeType(file.getPath()));
//            List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(shareIntent, 0);
//            if (!resInfo.isEmpty()) {
//                ArrayList<Intent> targetIntents = new ArrayList<Intent>();
//                for (ResolveInfo info : resInfo) {
//                    ActivityInfo activityInfo = info.activityInfo;
//                    if (activityInfo.packageName.contains("com.tencent.mobileqq")
//                            || activityInfo.packageName.contains("com.tencent.mm")) {
//                        Intent intent = new Intent(Intent.ACTION_SEND);
//                        intent.setPackage(activityInfo.packageName);
//                        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
//                        intent.setClassName(activityInfo.packageName, activityInfo.name);
//                        targetIntents.add(intent);
//                    }
//
//
//                }
//                Intent chooser = Intent.createChooser(targetIntents.remove(0), "Send mail...");
//                chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[]{}));
//                context.startActivity(chooser);
//
//            }
            context.startActivity(Intent.createChooser(shareIntent, "Send  文件。。"));
        }

    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param filePath
     */
    public static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "text/plain";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }
}